﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;

public class RZEditerComponent
{
    class OrderData { public int order; }

    private static Renderer m_Renderer;

    private static SortingGroup m_sortingGroup;

    [MenuItem ("RZTools/更新渲染顺序 &m")]
    private static void RenderSorting()
    {
        var scene = EditorSceneManager.GetActiveScene ();
        OrderData orders = new OrderData ();
        orders.order = 0;

        var list = scene.GetRootGameObjects ();
        int len = list.Length;

        for (int i = 0; i < len; i++)
        {
            var sr = list[i].GetComponent<SpriteRenderer> ();

            if (sr != null) sr.sortingOrder = orders.order++;
            else
            {
                var canvas = list[i].GetComponent<Canvas> ();
                if (canvas != null) canvas.sortingLayerID = orders.order++;
            }
            ChildrenEach (list[i].transform, orders);
        }
    }

    private static void ChildrenEach(Transform transform, OrderData order)
    {
        int len = transform.childCount;

        for (int i = 0; i < len; i++)
        {
            var sr = transform.GetChild (i).GetComponent<SpriteRenderer> ();

            if (sr != null) sr.sortingOrder = order.order++;
            else
            {
                var canvas = transform.GetChild (i).GetComponent<Canvas> ();
                if (canvas != null) canvas.sortingLayerID = order.order++;

            }

            ChildrenEach (transform.GetChild (i), order);
        }
    }
}